package edu.midir.demo.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author yangzhi
 */
public class ImageMarkUtil {
    /**
     * 水印透明度
     */
    private static float alpha = 0.5f;

    /**
     * 水印横向位置
     */
    private static int positionWidth = 150;

    /**
     * 水印纵向位置
     */
    private static int positionHeight = 300;

    /**
     * 水印文字字体
     */
    private static Font font = new Font("宋体", Font.BOLD, 30);

    /**
     * 水印文字颜色
     */
    private static Color color = Color.red;
    /**
     * 水印透明度
     */
    private static int interval = 0;

    private static final Logger logger = LoggerFactory.getLogger(ImageMarkUtil.class);

    /**
     * 设置水印参数，不设置就使用默认值
     *
     * @param alpha    水印透明度
     * @param interval 水印图片间隔
     * @param font     水印文字字体
     * @param color    水印文字颜色
     */
    public static void setImageMarkByFontOptions(float alpha, int interval, Font font, Color color) {
        if (alpha != 0.0f) {
            ImageMarkUtil.alpha = alpha;
        }
        if (interval != 0f) {
            ImageMarkUtil.interval = interval;
        }
        if (font != null) {
            ImageMarkUtil.font = font;
        }
        if (color != null) {
            ImageMarkUtil.color = color;
        }
    }

    /**
     * @param alpha          水印透明度
     * @param positionWidth  水印横向位置
     * @param positionHeight 水印纵向位置
     * @param font           水印文字字体
     * @param color          水印文字颜色
     *                       no use
     */
    public static void setImageMarkOptions(float alpha, int positionWidth, int positionHeight, Font font, Color color) {
        if (alpha != 0.0f) {
            ImageMarkUtil.alpha = alpha;
        }
        if (positionWidth != 0) {
            ImageMarkUtil.positionWidth = positionWidth;
        }
        if (positionHeight != 0) {
            ImageMarkUtil.positionHeight = positionHeight;
        }
        if (font != null) {
            ImageMarkUtil.font = font;
        }
        if (color != null) {
            ImageMarkUtil.color = color;
        }
    }

    /**
     * 平铺水印
     *
     * @param icon   水印
     * @param srcImg 原图
     * @param degree 角度 an angle, in degrees
     */
    public static BufferedImage markImageByIcon(BufferedImage icon, BufferedImage srcImg, Integer degree) {
        BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),
                srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
        // 1、得到画笔对象
        Graphics2D g = buffImg.createGraphics();
        // 2、设置对线段的锯齿状边缘处理
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        // 绘制原图
        g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);
        // 3、设置水印旋转
        if (null != degree) {
            g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);
        }
        // 4、水印图片的路径 水印图片一般为gif或者png的，这样可设置透明度
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
        // 画一个
//        g.drawImage(img, positionWidth, positionHeight, null);
        // 平铺该水印
        for (int height = interval + icon.getHeight(); height < buffImg
                .getHeight(); height = height + interval + icon.getHeight()) {

            for (int weight = interval + icon.getWidth(); weight < buffImg
                    .getWidth(); weight = weight + interval + icon.getWidth()) {
                g.drawImage(icon, weight - icon.getWidth(), height - icon.getHeight(), null);
            }

        }
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
        // 7、释放资源
        g.dispose();

        logger.info("图片完成添加水印图片");
        return buffImg;
    }
    /**
     * 该方法直接改变引用对象
     * @param original 原图
     * @param watermarkText 文本
     * @param degree 旋转角度 是个负数，和数学里的是反的
     * @param color 颜色 请用4个参数的 是个负数，和数学里的是反的
     * @param font 字体
     * @param paddingFontRate 间距控制
     */
    public static void watermark(BufferedImage original, String watermarkText,
                                 double degree,Color color,Font font,Integer paddingFontRate) {
        // create graphics context and enable anti-aliasing
        Graphics2D g2d = original.createGraphics();
        g2d.scale(1, 1);
        g2d.addRenderingHints(
                new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON));
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // create watermark text shape for rendering
        GlyphVector fontGV = font.createGlyphVector(g2d.getFontRenderContext(), watermarkText);
        Rectangle size = fontGV.getPixelBounds(g2d.getFontRenderContext(), 8, 8);
        Shape textShape = fontGV.getOutline();
        double textWidth = size.getWidth();
        double textHeight = size.getHeight();
        AffineTransform rotate45 = AffineTransform.getRotateInstance(Math.toRadians(degree));
        Shape rotatedText = rotate45.createTransformedShape(textShape);

        // use a gradient that repeats 4 times
        g2d.setPaint(new GradientPaint(0, 0, color,
                original.getWidth() / 2, original.getHeight() / 2,
                new Color(1f, 1f, 1f, 0.1f)));
        g2d.setStroke(new BasicStroke(0.5f));

        // step in y direction is calc'ed using pythagoras + 5 pixel padding
        double yStep = Math.sqrt(textWidth * textWidth / 2) + 5;

        // step over image rendering watermark text
        int rate = paddingFontRate == null ? 3 : paddingFontRate;
        for (double x = -textHeight * rate; x < original.getWidth(); x += (textHeight * rate)) {
            double y = -yStep;
            for (; y < original.getHeight(); y += yStep) {
                g2d.draw(rotatedText);
                g2d.fill(rotatedText);
                g2d.translate(0, yStep);
            }
            g2d.translate(textHeight * rate, -(y + yStep));
        }

    }


    public static void main(String[] args) {
        try {

            BufferedImage read = ImageIO.read(new File("C:\\Users\\dell\\Desktop\\1.jpeg"));
//            BufferedImage icon = ImageIO.read(new File("C:\\Users\\dell\\Desktop\\logo.png"));

            Color color = new Color(33, 193, 234, 50);
            int fontSize = (read.getHeight() + read.getWidth()) / 30;
            ImageMarkUtil.watermark(read, "智慧财",-30
                    ,color,new Font("宋体",Font.BOLD,fontSize),4);
            //文件上传文件名称，
            File file=new File("c:/Users/dell/desktop/2.png");
            FileOutputStream out=new FileOutputStream(file);
            ImageIO.write(read,"png",file);
            System.out.println("success");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}